#include <atomic>
#include <thread>
#include <iostream>

class SpinLock {
private:
    std::atomic_flag flag = ATOMIC_FLAG_INIT;

public:
    void lock() {
        while (flag.test_and_set(std::memory_order_acquire));  // 等待直到锁被释放
    }

    void unlock() {
        flag.clear(std::memory_order_release);
    }
};

void task(SpinLock& spinlock) {
    spinlock.lock();
    // 执行临界区代码
    std::cout << "Thread " << std::this_thread::get_id() << " entered critical section.\n";
    spinlock.unlock();
}

int main() {
    SpinLock spinlock;
    std::thread t1(task, std::ref(spinlock));
    std::thread t2(task, std::ref(spinlock));

    t1.join();
    t2.join();

    return 0;
}